<template>
  <fs-page class="fs-page-warp">
    <fs-crud ref="crudRef" v-bind="crudBinding">
      <template #form_menuList="scope">
        <el-tree-select
          :data="menuList"
          v-model="scope.form.menuList"
          node-key="id"
          multiple
          show-checkbox
          ref="menu"
          @change="nodeClick"
          highlight-current
          default-expand-all
          :collapse-tags="scope.mode !== 'view'"
          :props="defaultProps"
        />
      </template>
      <template #form_deptList="scope">
        <el-tree-select
          :data="deptTreeList"
          v-model="scope.form.deptList"
          node-key="id"
          multiple
          show-checkbox
          ref="deptTree"
          @change="deptClick"
          highlight-current
          default-expand-all
          :collapse-tags="scope.mode !== 'view'"
          :props="defaultProps"
        />
      </template>
    </fs-crud>
  </fs-page>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted } from "vue";
import {
  AddReq,
  CreateCrudOptionsProps,
  CreateCrudOptionsRet,
  DelReq,
  dict,
  EditReq,
  useFs,
  UserPageQuery,
  UserPageRes
} from "@fast-crud/fast-crud";
import {
  putV1OmsRole,
  postV1OmsRole,
  getV1OmsRolePage,
  deleteV1OmsRoleDetail
} from "@/api/oms/role";
import { convertTreeToCustomFields } from "@/utils/tree";
let menuCheckedList = [];
let deptListCheckedList = [];
import { ElLoading } from "element-plus";
import { hasAuth } from "@/router/utils";
import { getV1OmsDeptTree } from "@/api/oms/dept";
import { getV1OmsMenuTree } from "@/api/oms/menu";
//此处为crudOptions配置
const createCrudOptions = function ({
  crudExpose
}: CreateCrudOptionsProps): CreateCrudOptionsRet {
  //本地模拟后台crud接口方法 ----开始

  const pageRequest = async (query: UserPageQuery): Promise<UserPageRes> => {
    const { data } = await getV1OmsRolePage({
      ...query.page,
      ...query.form,
      pageNumber: query.page.currentPage
    });
    return {
      records: data.result,
      currentPage: query.page.pageNumber,
      pageSize: query.page.pageSize,
      total: data.total
    };
  };

  const editRequest = async ({ form, row }: EditReq) => {
    const { data } = await putV1OmsRole({ id: row.id, ...form });
    return data.result;
  };

  const delRequest = async ({ row }: DelReq) => {
    const { data } = await deleteV1OmsRoleDetail(row);
    return data.result;
  };
  function filterParentNodes(arr, tree) {
    const result = [];

    for (const node of tree) {
      if (
        arr.includes(node.id) &&
        node.children &&
        node.children.length === 0
      ) {
        result.push(node.id);
      }

      if (node.children && node.children.length > 0) {
        result.push(...filterParentNodes(arr, node.children));
      }
    }

    return result;
  }
  const addRequest = async ({ form }: AddReq) => {
    const { data } = await postV1OmsRole(form);
    return data.result;
  };
  function wait(time) {
    return new Promise(resolve => setTimeout(resolve, time));
  }
  const onRowBtnClick = async rowHandle => {
    if (rowHandle.mode === "edit") {
      await wait(100);
      const loading = ElLoading.service({
        lock: true,
        text: "加载中",
        target: ".el-drawer",
        background: "rgba(0, 0, 0, 0.7)"
      });
      const values = await Promise.all([
        await getV1OmsMenuTree(),
        await getV1OmsDeptTree()
      ]);
      const data = rowHandle.initialForm;
      const { data: menuData } = values[0];
      const { data: deptResult } = values[1];
      // const { obj } = await getV1OmsRoleDetail({ id: rowHandle.initialForm.id });
      // const { data } = await getV1OmsMenuTree();
      menuCheckedList = data.menuList;
      deptListCheckedList = data.deptList;
      const treeList = menuData.result;
      const deptTreeList = deptResult.result;
      if (rowHandle.mode === "view") {
        crudExpose.getFormWrapperRef().formOptions.columns.menuList.col.span = 24;
        crudExpose.getFormWrapperRef().formOptions.columns.deptList.col.span = 24;
      } else {
        crudExpose.getFormWrapperRef().formOptions.columns.menuList.col.span = 12;
        crudExpose.getFormWrapperRef().formOptions.columns.deptList.col.span = 12;
      }
      const menuList = filterParentNodes(data.menuList || [], treeList);
      const deptList = filterParentNodes(data.deptList || [], deptTreeList);
      crudExpose.setFormData({
        ...data,
        menuList: [...new Set(menuList)],
        deptList: [...new Set(deptList)]
      });
      loading.close();
    } else {
      menuCheckedList = [];
      deptListCheckedList = [];
      setTimeout(() => {
        crudExpose.getFormWrapperRef().formOptions.columns.menuList.col.span = 12;
        crudExpose.getFormWrapperRef().formOptions.columns.deptList.col.span = 12;
      }, 300);
    }
  };
  return {
    crudOptions: {
      request: {
        pageRequest,
        editRequest,
        delRequest,
        addRequest
      },
      form: {
        wrapper: {
          is: "el-drawer",
          size: "800px",
          onOpen: onRowBtnClick
        },
        beforeSubmit: context => {
          context.form.menuList = menuCheckedList;
          context.form.deptList = deptListCheckedList;
        },
        initialForm: {},
        labelPosition: "right",
        labelWidth: "120px" //表单label宽度
      },
      actionbar: {
        buttons: {
          add: {
            show: hasAuth("oms:role:add")
          }
        }
      },
      search: { autoSearch: false },
      rowHandle: {
        fixed: "right",
        buttons: {
          view: {
            show: hasAuth("oms:role:detail"),
            type: "success",
            plain: true
          },
          edit: { show: hasAuth("oms:role:update"), plain: true },
          remove: { show: hasAuth("oms:role:remove"), plain: true }
        }
      },
      columns: {
        id: {
          title: "记录ID",
          type: "text",
          search: { show: false },
          column: {
            show: false,
            resizable: true,
            minWidth: 140,
            align: "center"
          },
          editForm: { show: false },
          addForm: { show: false }
        },
        name: {
          title: "角色名称",
          type: "text",
          search: { show: true },
          column: {
            show: true,
            resizable: true,
            minWidth: 140,
            align: "center"
          },
          editForm: { rules: [{ required: true, message: "请输入角色名称" }] },
          addForm: { rules: [{ required: true, message: "请输入角色名称" }] }
        },
        key: {
          title: "角色权限字符串",
          type: "text",
          search: { show: false },
          column: {
            show: true,
            resizable: true,
            minWidth: 140,
            align: "center"
          },
          editForm: {
            rules: [{ required: true, message: "请输入角色权限字符串" }]
          },
          addForm: {
            rules: [{ required: true, message: "请输入角色权限字符串" }]
          }
        },
        status: {
          title: "角色状态",
          type: "dict-radio",
          search: { show: false },
          column: {
            show: true,
            resizable: true,
            minWidth: 140,
            align: "center"
          },
          dict: dict({
            data: [
              { value: false, label: "停用" },
              { value: true, label: "正常" }
            ]
          }),
          editForm: { rules: [{ required: true, message: "请选择角色状态" }] },
          addForm: {
            value: true,
            rules: [{ required: true, message: "请选择角色状态" }]
          }
        },
        deptList: {
          title: "所属部门",
          type: "dict-cascader",
          form: {
            col: {
              span: 12
            },
            component: {
              filterable: true,
              props: {
                props: {
                  "show-checkbox": true,
                  collapse: true,
                  multiple: true,
                  emitPath: false,
                  checkStrictly: true
                }
              },
              defaultExpandAll: true,
              clearable: false,
              multiple: true,
              collapseTags: false,
              "show-checkbox": true,
              checkStrictly: true
            }
          },
          dict: dict({
            isTree: true,
            label: "label",
            value: "id",
            getData: async () => {
              // 覆盖全局获取字典请求配置
              const { data } = await getV1OmsDeptTree();
              return convertTreeToCustomFields(
                [{ id: "0", name: "lafPureAdmin", children: data.result }],
                {
                  id: "id",
                  parent: "parentDeptId",
                  name: "name"
                }
              );
            }
          }),
          search: { show: false },
          column: {
            show: false,
            resizable: true,
            minWidth: 140,
            align: "center"
          },
          editForm: { rules: [{ required: true, message: "请选择部门" }] },
          addForm: {
            value: [],
            rules: [{ required: true, message: "请选择部门" }]
          }
        },

        menuList: {
          title: "菜单权限",
          type: "dict-cascader",
          form: {
            col: {
              span: 12
            },
            component: {
              filterable: true,
              props: {
                props: {
                  "show-checkbox": true,
                  collapse: true,
                  multiple: true,
                  emitPath: false,
                  checkStrictly: true
                }
              },
              defaultExpandAll: true,
              clearable: false,
              multiple: true,
              collapseTags: false,
              "show-checkbox": true,
              checkStrictly: true
            }
          },
          dict: dict({
            isTree: true,
            label: "name",
            value: "id",
            getData: async () => {
              // 覆盖全局获取字典请求配置
              const { data } = await getV1OmsMenuTree();
              return data.result;
            }
          }),
          search: { show: false },
          column: {
            show: false,
            resizable: true,
            minWidth: 140,
            align: "center"
          },
          editForm: { rules: [{ required: true, message: "请选择菜单权限" }] },
          addForm: {
            value: [],
            rules: [{ required: true, message: "请选择菜单权限" }]
          }
        },
        remark: {
          title: "备注",
          type: "textarea",

          form: {
            col: {
              span: 24
            }
          },
          search: { show: false },
          column: {
            show: true,
            resizable: true,
            minWidth: 140,
            align: "center"
          }
        },
        createTime: {
          title: "创建时间",
          type: "date",
          search: { show: false },
          column: {
            show: false,
            resizable: true,
            minWidth: 140,
            align: "center"
          },
          editForm: { show: false },
          addForm: { show: false }
        },
        created_at: {
          title: "编辑时间",
          type: "date",
          search: { show: false },
          column: {
            show: true,
            resizable: true,
            width: 200,
            align: "center",
            component: { format: "YYYY-MM-DD HH:mm:ss" }
          },
          editForm: { show: false },
          addForm: { show: false }
        }
      }
    }
  };
};
//此处为组件定义
export default defineComponent({
  name: "omsrole",
  setup() {
    // 演示自定义变量传递, 将会传递给createCrudOptions
    const customValue: any = {};
    const menuList = ref([]);
    const deptTreeList = ref([]);
    const menu = ref();
    const deptTree = ref();
    //  =======你可以简写为下面这一行========
    const { crudRef, crudBinding, crudExpose } = useFs({
      createCrudOptions,
      context: customValue
    });

    const defaultProps = {
      children: "children",
      label: "label",
      value: "id"
    };
    const getList = async () => {
      const { data } = await getV1OmsDeptTree();
      deptTreeList.value = convertTreeToCustomFields(data.result, {
        id: "id",
        parent: "parentDeptId",
        name: "name"
      });
    };
    // 页面打开后获取列表数据
    onMounted(async () => {
      crudExpose.doRefresh();
      // 覆盖全局获取字典请求配置
      getList();
      const { data } = await getV1OmsMenuTree();
      menuList.value = convertTreeToCustomFields(data.result, {
        id: "id",
        parent: "parentDeptId",
        name: "name"
      });
    });
    const nodeClick = () => {
      // 目前被选中的菜单节点
      const checkedKeys = menu.value.getCheckedKeys();
      // 半选中的菜单节点
      const halfCheckedKeys = menu.value.getHalfCheckedKeys();
      const mergedKeys = checkedKeys.concat(halfCheckedKeys);
      menuCheckedList = mergedKeys;
    };

    const deptClick = () => {
      // 目前被选中的菜单节点
      const checkedKeys = deptTree.value.getCheckedKeys();
      // 半选中的菜单节点
      const halfCheckedKeys = deptTree.value.getHalfCheckedKeys();
      const mergedKeys = checkedKeys.concat(halfCheckedKeys);
      deptListCheckedList = mergedKeys;
    };
    return {
      deptTreeList,
      deptTree,
      menu,
      deptClick,
      nodeClick,
      menuList,
      defaultProps,
      crudBinding,
      crudRef
    };
  }
});
</script>

<style lang="scss" scoped>
.fs-page-warp {
  :deep(.el-select__tags) {
    .el-tag__close {
      display: none;
    }
  }

  :deep(.el-cascader) {
    width: 100%;
  }
}
</style>
